package com.daigoudao.system;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.daigoudao.util.Constants;

/**
 * Servlet Filter implementation class FilterParamter
 */

public class FilterParamter implements Filter {
	String[] execuParamters = null;
	private boolean OK = true;
	private static Logger logger = LoggerFactory
			.getLogger(FilterParamter.class);

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hRequest = (HttpServletRequest) request;
		HttpServletResponse hResponse = (HttpServletResponse) response;
		
		//add date:2011-11-05
		HttpSession session = hRequest.getSession();
		if (session.getAttribute(Constants.USER_INFO) == null) {
			String key = (String) session.getAttribute(Constants.CAPTCHA_ID);
			if (key != null) {
				session.setAttribute(Constants.CAPTCHA_ID, key);
			}
		}

		
		boolean status = false;
		hResponse.setContentType("text/html");
		hResponse.setCharacterEncoding("utf-8");
		hRequest.setCharacterEncoding("utf-8");
		Enumeration<String> params = hRequest.getParameterNames();
		String param = "";
		String paramValue = "";
		while (params.hasMoreElements()) {
			param = params.nextElement();
			if (!"struts.token".equals(param)) {
				String[] values = request.getParameterValues(param);
				paramValue = "";
				if (OK) {// 过滤字符串为0个时 不对字符过滤
					for (int i = 0; i < values.length; i++) {
						paramValue = paramValue + values[i];
					}
					for (int i = 0; i < execuParamters.length; i++) {
						if (paramValue.indexOf(execuParamters[i]) >= 0) {
							status = true;
							break;
						}
					}
					if (status) {
						break;
					}

				}
			}
		}

		if (status) {
			logger.debug("输入了不合法的字符：" + paramValue);
			hResponse.getWriter().write(
					"<script>location.href='" + hRequest.getContextPath()
							+ "/invalidField.jsp';</script>");
			hResponse.getWriter().close();
		} else {
			chain.doFilter(hRequest, hResponse);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		String paramters = fConfig.getInitParameter("executParams");
		if (paramters != null && paramters.length() > 0) {
			execuParamters = paramters.split(",");
		} else {
			OK = false;
		}
	}

}
